<!--
 * @Description:
 * @Date: 2024-06-25 21:24:10
 * @LastEditTime: 2024-08-06 11:11:41
-->
<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="page" needLogin="false">
{
  style: {
    navigationBarTitleText: '',
  },
}
</route>
<template>
  <view class="bg-white overflow-hidden w-100% box-border">
    <view>
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell title="宣传照片（图片）" vertical prop="files">
          <wd-upload
            :file-list="model.files"
            :limit="6"
            multiple
            name="file"
            image-mode="aspectFill"
            :action="actions"
            @change="handleFileChange"
            @success="handleChange({ file: $event.file, type: 'cover' })"
            @remove="handleRemove({ file: $event.file, type: 'cover' })"
            class="bg-#fff"
          ></wd-upload>
        </wd-cell>
        <wd-cell title="店名" vertical prop="storeName">
          <wd-input
            v-model="model.storeName"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：景家民宿"
          />
        </wd-cell>
        <wd-cell title="商家标签" vertical prop="storeLabel">
          <wd-tag
            v-model="model.storeLabel"
            v-for="(tag, index) in tags"
            :key="index"
            custom-class="space"
            round
            closable
            @close="handleClose(index)"
          >
            {{ tag }}
          </wd-tag>
          <wd-tag
            v-if="tags.length < 3"
            custom-class="space"
            round
            dynamic
            @confirm="handleConfirm"
          ></wd-tag>
        </wd-cell>
        <wd-cell title="地址" vertical prop="storeAddr">
          <view
            class="bg-#1F6977 text-#fff border-rd-8rpx text-24rpx p-8rpx"
            @click="handleAddr"
            style="position: absolute; top: -42px; left: 50px"
          >
            点击自动获取
          </view>
          <wd-input
            v-model="model.storeAddr"
            :maxlength="50"
            :show-word-limit="true"
            placeholder="请填写详细地址"
          />
        </wd-cell>
        <wd-cell title="人均消费（元）" vertical prop="consumption">
          <wd-input
            v-model="model.consumption"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：100"
          />
        </wd-cell>
        <wd-cell title="联系电话" vertical prop="phone">
          <wd-input
            v-model="model.phone"
            :maxlength="20"
            :show-word-limit="true"
            placeholder="例如：18928743847"
          />
        </wd-cell>
        <view style="font-weight: bold; color: #333 !important; font-size: 28rpx" class="p-20rpx">
          推荐菜
        </view>
        <view
          v-for="(food, index) in model.recommendFoods"
          :key="index"
          class="recommendFoods px--10rpx"
        >
          <wd-cell vertical title="菜品图片">
            <wd-upload
              :file-list="food.files"
              :limit="1"
              multiple
              name="file"
              image-mode="aspectFill"
              :action="actions"
              @change="handleFileChange"
              @success="handleChange({ file: $event.file, type: 'recommend', index: index })"
              @remove="handleRemove({ file: $event.file, type: 'recommend', index: index })"
              class="bg-#fff"
            ></wd-upload>
            <view
              style="position: absolute; top: -36px; left: -10px; color: #fa4350; font-size: 24rpx"
            >
              *
            </view>
            <!-- <view v-if="showFiles" style="color: #fa4350; font-size: 24rpx">请上传菜品图片</view> -->
          </wd-cell>
          <wd-cell vertical title="菜品名称：" prop="name">
            <wd-input
              v-model="food.name"
              :maxlength="20"
              :show-word-limit="true"
              placeholder="西红柿炒鸡蛋"
            />
            <view
              style="position: absolute; top: -36px; left: -10px; color: #fa4350; font-size: 24rpx"
            >
              *
            </view>
            <!-- <view v-if="showName" style="color: #fa4350; font-size: 24rpx">请输入菜品名称</view> -->
          </wd-cell>
          <wd-cell title="价格：" vertical prop="price">
            <wd-input
              v-model="food.price"
              :maxlength="20"
              :show-word-limit="true"
              placeholder="12"
            />
            <view
              style="position: absolute; top: -36px; left: -10px; color: #fa4350; font-size: 24rpx"
            >
              *
            </view>
            <!-- <view v-if="showPrice" style="color: #fa4350; font-size: 24rpx">请输入菜品价格</view> -->
          </wd-cell>
          <wd-cell vertical title="菜品描述：" prop="remark">
            <wd-textarea
              v-model="food.remark"
              :maxlength="200"
              :show-word-limit="true"
              placeholder="酸甜开胃，口感滑嫩"
            />
            <view
              style="position: absolute; top: -36px; left: -10px; color: #fa4350; font-size: 24rpx"
            >
              *
            </view>
            <!-- <view v-if="showPrice" style="color: #fa4350; font-size: 24rpx">请输入菜品描述</view> -->
          </wd-cell>
        </view>
        <view class="flex items-center justify-between p-20rpx">
          <!-- 增加推荐菜的按钮 -->
          <view
            class="bg-#F7F7F7 100% py-10rpx px-150rpx text-#646464 border-rd-8rpx text-32rpx"
            style="border-color: #646464"
            @click="addRecommendFood"
          >
            +
          </view>
          <view
            v-if="model.recommendFoods.length > 0"
            class="bg-#F7F7F7 100% py-10rpx px-150rpx text-#646464 border-rd-8rpx text-32rpx"
            style="border-color: #646464; margin-left: 20rpx"
            @click="removeRecommendFood"
          >
            -
          </view>
        </view>
      </wd-form>
      <view class="question-btn flex items-center justify-between">
        <wd-button plain hairline @click="submitHandler">提交</wd-button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { useToast } from 'wot-design-uni'
import { cerateCuisine, updateCuisine } from '@/service/TouristManagement/MyCuisine'
import { useUserStore } from '@/store'
import _ from 'lodash'
const reportType = ref(1)
const userStore = useUserStore()
const toast = useToast()
const baseurl = ref(import.meta.env.VITE_SERVER_BASEURL)
const actions: string = baseurl.value + '/app-api/infra/file/business/upload'
const form = ref()
const showButton = ref(false)
const showType = ref()
const saveId = ref()
const userId = computed(() => userStore.userInfo.userId)

const model = reactive<{
  storeName: string
  storeLabel: string
  files: any[]
  storeAddr: string
  consumption: string
  phone: string
  recommendFoods: Array<{ name: string; price: string; remark: string; files: any[] }>
}>({
  storeName: '',
  storeLabel: '',
  storeAddr: '',
  consumption: '',
  phone: '',
  recommendFoods: [{ name: '', price: '', remark: '', files: [] }],
  files: [],
})
const compress = true
const rules: FormRules = {
  storeName: [
    {
      required: true,
      message: '请输入店名',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入店名'))
        }
      },
    },
  ],
  storeLabel: [
    {
      required: true,
      message: '请输入商家标签',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入商家标签'))
        }
      },
    },
  ],
  files: [
    {
      value: model.files,
      required: true,
      message: '请输入宣传照片',
      validator: (value) => {
        if (value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject('请输入宣传照片')
        }
      },
    },
  ],
  storeAddr: [
    {
      required: true,
      message: '请输入地址',
      validator: (value) => {
        value = value.trim()
        if (!value) {
          return Promise.reject('请输入地址')
        }
        if (/^\d+$/.test(value)) {
          return Promise.reject(new Error('地址不能是纯数字'))
        } else {
          return Promise.resolve()
        }
      },
    },
  ],
  consumption: [
    {
      required: true,
      message: '请输入人均消费',
      trigger: 'change',
      validator: (value, rule) => {
        value = value.trim()
        if (!value) {
          return Promise.reject(new Error('请输入人均消费'))
        }

        const regex = /^\d+(\.\d{1,2})?$/
        if (!regex.test(value)) {
          return Promise.reject(new Error('小数点后不超过两位'))
        }
        const numValue = parseFloat(value)
        if (isNaN(numValue) || numValue > 1000) {
          return Promise.reject(new Error('人均消费必须是有效的数字且不能超过1000'))
        }
        return Promise.resolve(true)
      },
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入联系电话',
      validator: (value) => {
        if (!value) {
          return Promise.reject(new Error('请输入联系电话'))
        }
        // 使用正则表达式验证手机号码格式
        const regex = /^1(3|4|5|6|7|8|9)\d{9}$/
        if (!regex.test(value)) {
          return Promise.reject(new Error('手机号码格式不正确'))
        }
        return Promise.resolve(true)
      },
    },
  ],
}
const validateRecommendFoods = () => {
  let isValid = true
  model.recommendFoods.forEach((food, index) => {
    if (food.files.length === 0 || !food.name || !food.name || !food.price) {
      isValid = false
    }
  })
  return isValid
}
defineOptions({
  name: 'addCuisine',
})
// 标签
const tags = ref([])

function handleClose(order) {
  tags.value = tags.value.filter((value, index) => index !== order)
}

function handleConfirm({ value }) {
  if (!value) return
  tags.value = [...tags.value, value]
}
// 增加推荐菜的方法
function addRecommendFood() {
  model.recommendFoods.push({ name: '', price: '', remark: '', files: [] })
}

// 减少推荐菜的方法
function removeRecommendFood() {
  if (model.recommendFoods.length > 0) {
    model.recommendFoods.pop() // 移除最后一个推荐菜
  }
}
// 获取位置
const longitude = ref()
const latitude = ref()
const latAndLon = ref('')
// 自动获取地址
const handleAddr = async () => {
  uni.getLocation({
    type: 'wgs84',
    success: (res) => {
      longitude.value = res.longitude
      latitude.value = res.latitude
      latAndLon.value = longitude.value + ',' + latitude.value

      const key = '3a03083007a21041fa2cea8bffdca493' // 替换为你的API密钥
      const url = `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude.value},${latitude.value}&key=${key}`
      uni.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            const data = res.data
            if (data.status === '1' && data.regeocode) {
              const geocode = data.regeocode
              const address = geocode.formatted_address
              model.storeAddr = address
            } else {
              console.error('获取地址失败：', data.info)
            }
          } else {
            console.error('请求失败：', res.statusCode)
          }
        },
        fail: (err) => {
          console.error('请求失败：', err)
        },
      })
    },
    fail: (err) => {
      console.error('获取位置失败：', err)
    },
  })
}
// 获取经纬度
const getLatAndLon = async () => {
  const key = '3a03083007a21041fa2cea8bffdca493' // 替换为你的API密钥
  const url = `https://restapi.amap.com/v3/geocode/geo?key=${key}&address=${encodeURIComponent(model.storeAddr)}`
  try {
    const res = await new Promise((resolve, reject) => {
      uni.request({
        url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(new Error('请求失败：' + res.statusCode))
          }
        },
        fail: (err) => {
          reject(new Error('请求失败：' + err))
        },
      })
    })

    const data = res
    console.log(data, 'data')
    if (data.status === '1' && data.geocodes[0]) {
      latAndLon.value = data.geocodes[0].location
    } else {
      console.error('获取地址失败：', data.info)
      throw new Error('获取地址失败：' + (data.info || '未知错误'))
    }
  } catch (error) {
    console.error('获取地址过程中发生错误：', error)
    throw error
  }
}
function handleChange({ file, type = 'cover', index = null }) {
  if (type === 'cover') {
    const { response } = file
    const fileId = JSON.parse(response).data.id
    file.fileId = fileId
    model.files.push(file)
  } else {
    const { response } = file
    const fileId = JSON.parse(response).data.id
    file.fileId = fileId
    if (index !== null && model.recommendFoods[index]) {
      model.recommendFoods[index].files = [file]
    }
  }
}
function handleFileChange({ fileList }) {
  //   model.fileList = fileList
}
function handleRemove({ file, type = 'cover', index = null }) {
  if (type === 'cover') {
    // 移除宣传照片
    model.files = model.files.filter((item) => item.uid !== file.uid)
  } else {
    // 移除指定推荐菜的图片
    if (index !== null) {
      model.recommendFoods[index].files = model.recommendFoods[index].files.filter(
        (item) => item.uid !== file.uid,
      )
    }
  }
}
const idList = ref([])
const ids = ref([])
const submitHandler = _.debounce(() => {
  handleSubmit()
}, 1000)
const handleSubmit = async () => {
  model.storeLabel = tags.value.join(',')

  // 宣传图片
  const fileIds = ref([])
  // eslint-disable-next-line array-callback-return
  model.files.forEach((item) => {
    if (item.fileId) {
      fileIds.value.push(item.fileId)
    }
    if (item.id) {
      fileIds.value.push(item.id)
    }
  })

  const newFilesSet = [...new Set(fileIds.value)]
  idList.value = newFilesSet

  // 推荐菜
  const foodArr = model.recommendFoods.map((item) => {
    const firstFile = item.files && item.files.length > 0 ? item.files[0] : null
    const fileId = firstFile ? firstFile.fileId || firstFile.id : undefined
    return {
      ...item,
      files: [fileId],
    }
  })
  ids.value = [...foodArr]

  try {
    const { valid, errors } = await form.value.validate()
    if (!valid) {
      toast.error({ msg: '请检查必选项是否填写', duration: 2000 })
      return
    }
    await getLatAndLon()
    if (!validateRecommendFoods()) {
      toast.error({ msg: '请填写所有推荐菜品的必要信息', duration: 2000 })
      return
    }
    if (model.recommendFoods.length === 0) {
      toast.error({ msg: '至少有一个推荐菜', duration: 2000 })
      return
    }

    const creatorVo = {
      userId: userId.value,
    }
    const apiCall = showType.value === 'add' ? cerateCuisine : updateCuisine

    // 调用API
    try {
      await apiCall({
        ...model,
        ...creatorVo,
        id: saveId.value,
        files: idList.value,
        recommendFoods: ids.value,
        latAndLon: latAndLon.value,
      })
      toast.success({ msg: '操作成功', duration: 2000 })
      setTimeout(() => {
        uni.navigateBack({ delta: 1 })
        toast.close()
      }, 1000)
    } catch (error) {
      toast.error({ msg: '提交失败', duration: 2000 })
    }
  } catch (validationError) {
    console.error('验证过程发生错误:', validationError)
    toast.error({ msg: '表单验证异常', duration: 2000 })
  }
}

onLoad((options) => {
  showType.value = options.type
  if (options.type === 'edit') {
    const item = JSON.parse(decodeURIComponent(options.data || '{}'))
    saveId.value = item.id
    model.storeName = item.storeName
    tags.value = item.storeLabel
    model.storeAddr = item.storeAddr
    model.consumption = item.consumption
    model.phone = item.phone
    model.files = item.fileDOList.map((val) => {
      return { ...val, url: baseurl.value + val.url }
    })
    model.recommendFoods = item.recommendFoods.map((food, index) => {
      food.files = food.fileDOList
        .filter((val) => val && val.url)
        .map((val) => ({
          ...val,
          url: baseurl.value + val.url,
        }))
      return {
        ...food,
      }
    })
  }
})
</script>

<style lang="scss" scoped>
.videoCard {
  background: rgba(0, 0, 0, 0.04);
}
::v-deep .wd-icon-sound {
  margin-right: 20rpx;
}
::v-deep .wd-textarea {
  padding: 0 !important;
}
::v-deep .wd-textarea::after,
::v-deep .wd-input::after {
  height: 0 !important;
}

::v-deep .wd-textarea__value,
::v-deep .wd-input__value {
  padding: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-textarea__count,
::v-deep .wd-input__count {
  right: 20rpx !important;
  background: #f3f4f7 !important;
}
::v-deep .wd-cell__title {
  font-weight: bold !important;
  color: #333 !important;
}
::v-deep .wd-cell__right {
  margin-top: 20rpx !important;
}
::v-deep .wd-button {
  background: #029669 !important;
}
.question-btn {
  height: 100rpx;
  padding: 40rpx !important;
  text-align: center;
  box-shadow: 0px -3px 6px 0px rgba(201, 201, 201, 0.4);
}
.fixed-button {
  position: fixed;
  bottom: 0;
  left: 50%;
  z-index: 99;
  width: 100%;
  transform: translateX(-50%);
}
::v-deep.wd-button.is-plain.is-primary {
  width: 100%;
  border: none !important;
  border-radius: 18rpx !important;
  color: #fff !important;
}
::v-deep .wd-tag.is-default.is-round {
  border-radius: var(--wot-tag-round-radius, 8rpx) !important;
  line-height: 28rpx !important;
}
::v-deep .wd-tag.is-default.is-round:hover {
  color: #ad0e0e !important;
  border-color: #ad0e0e !important;
}
:deep(.space) {
  margin: 0 10rpx 10rpx;
}
::v-deep .wd-tag__close {
  vertical-align: baseline !important;
  line-height: 32rpx !important;
}
::v-deep .wd-tag__add {
  vertical-align: baseline !important;
}
::v-deep .wd-tag__text {
  vertical-align: baseline !important;
}
.recommendFoods {
  border-radius: 6rpx;
  background-color: rgba(255, 255, 255, 1);
  box-shadow: 0px 4rpx 12rpx 0px rgba(132, 132, 132, 0.4);
  margin: 0 20rpx;
  margin-bottom: 20rpx;
}
::v-deep .wd-upload__evoke {
  margin-bottom: 0;
}
::v-deep .wd-upload__mask {
  background: transparent !important;
}
</style>
